<!-- components/image-uploader.vue -->
<template>
  <view class="upload-container">
    <!-- 图片预览区域 -->
	<view v-if="tempFilePath" class="preview-wrapper">
	  <image :src="tempFilePath" mode="aspectFit" class="preview-image"></image>
	  <text class="replace-btn" @click="chooseImage">重新上传</text>
	</view>
    <view v-else-if="avatar" class="preview-wrapper">
      <image :src="getBaseUrl+avatar" mode="aspectFit" class="preview-image"></image>
      <text class="replace-btn" @click="chooseImage">重新上传</text>
    </view>

    <!-- 上传按钮 -->
    <view v-else class="upload-btn" @click="chooseImage">
      <text class="btn-text">+ 添加图片</text>
      <text class="tips-text">(仅支持jpg/png格式)</text>
    </view>

    <!-- 错误提示 -->
    <text v-if="errorMessage" class="error-msg">{{ errorMessage }}</text>
  </view>
</template>

<script setup>
	import getBaseUrl from '../utils/baseUrl'
import { ref } from 'vue'
import { http } from '../utils/requestUtil';

const props = defineProps({
  uploadUrl: String,// 上传接口地址
  avatar:String //
})
// console.log(avatar+'12222222')
const emit = defineEmits(['upload-complete'])

const tempFilePath = ref('')
const errorMessage = ref('')

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'],
      extension: ['jpg', 'png'] // 限制文件类型
    })

    const file = res.tempFiles[0]
    
    // 格式验证
    // if (!['image/jpeg', 'image/png'].includes(file.type)) {
    //   errorMessage.value = '只支持jpg/png格式图片'
    //   return
    // }

    // 大小限制（示例2MB）
    // if (file.size > 2 * 1024 * 1024) {
    //   errorMessage.value = '图片大小不能超过2MB'
    //   return
    // }

    errorMessage.value = ''
    tempFilePath.value = res.tempFilePaths[0]
  } catch (err) {
    console.error('选择图片失败:', err)
  }
}

// 执行上传（由父组件触发）
const handleUpload = async () => {
  if (!tempFilePath.value) {
	  return  { success: true, data: '未选择图片' }
    // return { success: false, message: '请先选择图片' }
  }
console.log(tempFilePath.value)
  try {
    const uploadRes = await http.upload(
     '/common/upload',
      tempFilePath.value
      // name: 'file'
    )

    console.log(uploadRes)
    emit('upload-complete', uploadRes)
    return { success: true, data: uploadRes.fileName }
  } catch (err) {
    console.error('上传失败:', err)
    return { success: false, message: '图片格式不符(请选择jpg、png图片)' }
  }
}

// 暴露方法给父组件
defineExpose({ handleUpload })
</script>

<style scoped>
.upload-container {
  padding: 20rpx;
  text-align: center;
}

.upload-btn {
  width: 300rpx;
  height: 300rpx;
  border: 2rpx dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0 auto;
}

.preview-wrapper {
  position: relative;
  width: 300rpx;
  margin: 0 auto;
}

.preview-image {
  width: 300rpx;
  height: 300rpx;
  border-radius: 8rpx;
}

.replace-btn {
  position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  background: rgba(0,0,0,0.5);
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.error-msg {
  color: #ff4444;
  font-size: 24rpx;
  display: block;
  margin-top: 16rpx;
}

.tips-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}
</style>